<?php

namespace App\Http\Middleware;

use App\Models\Partner\Partner;
use Closure;

class PartnerAuth
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $data = $request->input();

        try {
            $this->verifySign($data);
        } catch (\Exception $e) {
            return Response()->json([
                'success' => false,
                'message' => $e->getMessage(),
                'code' => '',
            ], 200);
        }

        return $next($request);
    }

    // 获取sign
    function getSign($secret, $data)
    {
        // 对数组的值按key排序
        ksort($data);
        // 生成url的形式
        $params = http_build_query($data);
        // 生成sign
        $sign = md5($params . $secret);

        return $sign;
    }

    //延签
    function verifySign($data)
    {
        try {
            // 验证参数中是否有签名
            if (!isset($data['sign']) || !$data['sign']) throw new \Exception('发送的数据签名不存在');
            if (!isset($data['timestamp']) || !$data['timestamp']) throw new \Exception('发送的数据参数不合法');
            if (!isset($data['platform']) || !$data['platform']) throw new \Exception('platform不存在');
            // 验证请求， 10分钟失效
            if (time() - $data['timestamp'] > 600) throw new \Exception('验证失效， 请重新发送请求');

            $partner = Partner::where('platform', $data['platform'])->first();
            if (!$partner) throw new \Exception('platform不存在');
            if ($partner->state != 1) throw new \Exception('platform:' . Partner::$stateArr[$partner->state]);

            $sign = $data['sign'];
            unset($data['sign']);

            $sign2 = $this->getSign($partner->secret, $data);

            if ($sign != $sign2) throw new \Exception('签名错误');

            return true;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }
}
